package com.atguigu.demo2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/8
 * @desc 有一个温度为0的空调，现有4个人对该空调进行操作，实现2个人对温度加1，2个对温度减1，交替来10次
 */
public class ProdConsumerDemo {
    public static void main(String[] args) {
        AirCondition air = new AirCondition();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                air.incr();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                air.decr();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                air.incr();
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                air.decr();
            }
        }, "D").start();
    }

}

/**
 * 空调，资源类
 */
class AirCondition {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    int number = 0;

    public void incr() {
        // 加锁
        lock.lock();
        try {
            // 判断
            while (number != 0) {
                // 增加温度的线程等待
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 工作
            number++;
            System.out.println(Thread.currentThread().getName() + "----" + number);
            // 通知
            condition.signalAll();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    public void decr() {
        lock.lock();
        try {
            // 判断
            while (number == 0) {
                // 减少温度的线程等待
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 工作
            number--;
            System.out.println(Thread.currentThread().getName() + "----" + number);
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}


